#!/usr/bin/ruby
$:.unshift File.join(File.dirname(__FILE__))
require 'AWS/S3'
require 'basic_configuration'
require 'aws_context'
require 'pp'

#  Put the contents of the given file into S3.
#  If the key name is supplied, then it is used.
#  Otherwise, the filename is used.
#  The bucket may be supplied as an option.

if ARGV[0] == '-?' || ARGV.size < 1 then
  puts "usage: put-object filename [key [bucket [metadata*]]]"
  exit
end
fname=ARGV[0]
if ARGV.size >= 2
  key = ARGV[1]
  if key == '-' then key = fname end
else
  key = fname
end
bucket = ARGV[2]
m = ARGV[3..-1]
if m
  metadata = {}
  m.each do |md|
    k, v = md.split(':')
    metadata[k] = v if k && v
      end
end

config = BasicConfiguration.new
if bucket.nil? || bucket == '-'
  bucket = config.aws[:aws_bucket]
end
if bucket.nil?
  puts "AWS_BUCKET environment variable must be set or defined in config file."
  exit 1
end

begin
  file = File.new(fname, 'r')
rescue
  puts "not found: #{fname}"
  exit 1
end

Signal.trap("INT") do
  exit 2
end

s3 = AwsContext.instance.s3(*config.keys)
begin
  opts = {:data => file, :access => "public-read"}
  opts[:metadata] = metadata if metadata
  obj = s3.create_object(bucket, key, opts)
  puts "stored #{fname} as #{key}"
rescue
  puts "error: #{$!} -- not stored"
  exit 1
end
